#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#include <time.h>
#define High 18
#define Width 30

int pos_x;   //鸟位置
int pos_y;
int bar_x,bardown,bartop; // 障碍物

char c;

int score;

int i, j;

int speed;  //下落速度




void gotoxy(int x,int y)  //光标移动到(x,y)位置
{
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    pos.X = x;
    pos.Y = y;
    SetConsoleCursorPosition(handle,pos);
}

void HideCursor() // 用于隐藏光标
{
	CONSOLE_CURSOR_INFO cursor_info = {1, 0};  // 第二个值为0表示隐藏光标
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}


void start (){
	score = 0;
	pos_x = Width / 2;   //鸟位置
	pos_y = High / 2;
	
	bar_x = Width;
	bardown = 3;
	bartop = 10;

	speed = 0;
	srand((unsigned int)time(NULL));

	HideCursor(); // 隐藏光标

}


void user (){
	if(kbhit()){  // 判断是否有输入
		c = getch();

		if (c == ' '){
			pos_y = pos_y - 2;
		}
		else if (c == 27){
			getch();
		}

	}
}


void show (){
	gotoxy(0,0);  // 光标移动到原点位置，以下重画清屏
	for (i = 1; i <= High; i ++){
		for (j = 1; j <= Width; j ++){

			if (i == pos_y && j == pos_x){                                
				printf ("@");
			}
			else if ((j == bar_x) && ((i < bardown)||(i > bartop)) )
				printf("*");  //   输出墙壁

			else if (j == Width){
				printf ("|");
			}
			else if (i == High){
				printf ("_");
			}

			else
				printf (" ");
			
		}
		printf("\n");
		
	}
	printf ("分数：%d", score);
	
	
}




void update (){
		speed ++;
		if (speed == 10){
			speed = 0;
			pos_y ++;
			bar_x --;
		}


		if (pos_x == bar_x)
		{
			if ((pos_y >= bardown) && (pos_y <= bartop))
				score++;
			else
			{
				printf("游戏失败\n");
				system("pause");
				exit(0);
			}
		}
		if (bar_x <= 0)  // 再新生成一个障碍物
		{
			bar_x = Width;
			int temp = rand()%int(High*0.8);
			bardown = temp - High/5;
			bartop = temp + High/5;
		}
		
		
		
		if (pos_y > High) {               
			printf("游戏失败\n");
			system("pause");
			exit(0);
		}
		
		if (pos_x < 1)
			pos_x ++;




}





int main(){
    start();
	while(1){
		show();
		user();
		update();

	}
	return 0;
}